package com.banmao.algorithm.No101To200.No105;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

public class Solution1 {

    private Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {

        // 将中序遍历的值和下标放入Map中
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }

        TreeNode node = findNode(preorder, 0, preorder.length, inorder, 0, inorder.length);

        return node;
    }

    private TreeNode findNode(int[] preorder, int preBeginIndex, int preEndIndex, int[] inorder, int inBeginIndex, int inEndIndex) {

        // 递归出口
        if (preBeginIndex >= preEndIndex || inBeginIndex >= inEndIndex) {
            return null;
        }

        Integer nodeIndex = map.get(preorder[preBeginIndex]);
        TreeNode node = new TreeNode(preorder[preBeginIndex]);
        int lenOfLeft = nodeIndex - inBeginIndex;

        node.left = findNode(preorder, preBeginIndex + 1, preBeginIndex + lenOfLeft + 1, inorder, inBeginIndex, nodeIndex);
        node.right = findNode(preorder, preBeginIndex + lenOfLeft + 1, preEndIndex, inorder, nodeIndex + 1, inEndIndex);

        return node;
    }

}

@Data
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
